<template>
  <div class="user-management">
    <div class="search-bar"> 
      <el-form-item label="姓名：" class="search-form-item">
        <el-input v-model="searchQuery" placeholder="请输入姓名" class="search-input" />
      </el-form-item>
      <el-form-item label="职业：" class="search-form-item">
        <el-input v-model="occupation" placeholder="请输入职业" class="search-input" />
      </el-form-item>
      <el-form-item label="年龄：" class="search-form-item">
        <el-input v-model.number="age" placeholder="请输入年龄" class="age-input" type="number" />
      </el-form-item>
      <el-form-item label="生日范围：" class="search-form-item">
        <el-date-picker v-model="birthdayRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="date-picker" />
      </el-form-item>
      <el-form-item label="性别：" class="search-form-item">
        <el-select v-model="gender" placeholder="请选择性别" style="width: 240px;">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="fetchFilteredUsers">查询</el-button>
    </div>

    <div class="add-user-button-container">
      <el-button type="success" @click="openAddDialog" :icon="Plus" circle />
    </div>

    <el-table :data="users" border style="width: 100%" stripe highlight-current-row size="medium" @row-dblclick="openEditDialog">
      <el-table-column prop="name" label="姓名" sortable />
      <el-table-column prop="age" label="年龄" sortable />
      <el-table-column prop="occupation" label="职业" />
      <el-table-column prop="birthday" label="生日" :formatter="formatBirthday" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="openEditDialog(row)" size="small" :icon="Edit" circle />
          <el-button @click="deleteUser(row.id)" size="small" type="danger" :icon="Delete" circle />
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalUsers"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 50]"
          prev-text="上一页"
          next-text="下一页"
          class="custom-pagination"
          @current-change="fetchFilteredUsers"
          @size-change="fetchFilteredUsers"
        />
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="form.age" type="number" />
        </el-form-item>
        <el-form-item label="职业" prop="occupation">
          <el-input v-model="form.occupation" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="form.birthday" type="date" format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 导入Vue核心函数、Element Plus组件和图标
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
// 导入用户服务模块，处理用户数据相关API请求
import { userService } from '../services/userService';

// 日期格式化函数：将日期对象转换为YYYY-MM-DD格式的字符串
// 参数：row - 包含birthday属性的行数据对象
const formatBirthday = (row) => {
  if (!row.birthday) return '';
  const date = new Date(row.birthday);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 搜索和分页相关的响应式变量
const searchQuery = ref(''); // 姓名搜索关键词
const occupation = ref(''); // 职业搜索关键词
const age = ref(null); // 年龄搜索条件
const birthdayRange = ref(null); // 生日范围搜索条件 [开始日期, 结束日期]
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示条数
const gender = ref(''); // 性别搜索关键词

// 用户数据相关的响应式变量
const users = ref([]); // 用户列表数据
const totalUsers = ref(0); // 总用户数，用于分页
const loading = ref(false); // 加载状态标志

// 根据筛选条件获取用户列表
// 构建筛选参数对象并调用fetchUsers方法
const fetchFilteredUsers = async () => {
  const filters = {
    page: currentPage.value,
    pageSize: pageSize.value
  };

  // 动态添加非空筛选条件
  if (searchQuery.value) filters.name = searchQuery.value;
  if (occupation.value) filters.occupation = occupation.value;
  if (age.value) filters.age = age.value;
  if (birthdayRange.value) {
    filters.birthdayStart = birthdayRange.value[0];
    filters.birthdayEnd = birthdayRange.value[1];
  }
  if (gender.value) filters.gender = gender.value;

  await fetchUsers(filters);
};

// 页面加载时自动获取用户列表
onMounted(async () => {
  await fetchFilteredUsers();
});

// 获取用户列表的核心方法
// 参数：filters - 筛选条件对象，包含分页和查询条件
const fetchUsers = async (filters = {}) => {
  loading.value = true; // 开始加载
  try {
    console.log('请求参数:', filters);
    const response = await userService.getList(filters);
    console.log('响应数据:', response);
    // 适配 com.baomidou.mybatisplus.extension.plugins.pagination.Page 对象
    users.value = response.records;
    totalUsers.value = response.total;
  } finally {
    loading.value = false; // 无论成功失败，结束加载状态
  }
};

// 对话框相关状态变量
const dialogVisible = ref(false); // 对话框显示状态
const dialogTitle = ref('添加用户'); // 对话框标题
const formRef = ref(null); // 表单引用，用于表单验证
// 用户表单数据对象
const form = reactive({
  id: null, // 用户ID，编辑时存在，添加时为null
  name: '', // 姓名
  age: null, // 年龄
  occupation: '', // 职业
  birthday: null, // 生日
  gender: '', // 性别
});

// 表单验证规则
// 定义各字段的验证条件和错误提示
const rules = {
  // 姓名验证：必填，失去焦点时触发，长度在2到10个字符之间
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  // 年龄验证：必填，数字类型，失去焦点时触发，范围在1到150之间
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 150, message: '年龄必须在 1 到 150 之间', trigger: 'blur' }
  ],
  // 职业验证：必填，失去焦点时触发，长度在2到20个字符之间
  occupation: [
    { required: true, message: '请输入职业', trigger: 'blur' },
    { min: 2, max: 20, message: '职业长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  // 生日验证：必填，日期变更时触发
  birthday: [
    { required: true, message: '请选择生日', trigger: 'change' }
  ], // Added missing comma
  // 性别验证：必填，选择变更时触发
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
};


// 打开添加用户对话框
// 重置表单数据并设置对话框标题
const openAddDialog = () => {
  dialogTitle.value = '添加用户';
  form.id = null;
  form.name = '';
  form.age = null;
  form.occupation = '';
  form.birthday = null;
  dialogVisible.value = true;
};

// 打开编辑用户对话框
// 参数：row - 要编辑的用户行数据
const openEditDialog = (row) => {
  dialogTitle.value = '编辑用户';
  // 将行数据赋值给表单
  form.id = row.id;
  form.name = row.name;
  form.age = row.age;
  form.occupation = row.occupation;
  form.birthday = row.birthday;
  form.gender = row.gender;
  dialogVisible.value = true;
};

// 保存用户（添加或编辑）
// 先验证表单，然后根据是否有ID决定调用添加或更新接口
const saveUser = async () => {
  await formRef.value.validate(); // 表单验证
  loading.value = true;
  try {
    if (form.id) {
      // 编辑现有用户
      await userService.update(form.id, form);
      ElMessage.success('用户更新成功');
    } else {
      // 添加新用户
      await userService.create(form);
      ElMessage.success('用户添加成功');
    }
    dialogVisible.value = false; // 关闭对话框
    await fetchUsers(); // 刷新用户列表
  } finally {
    loading.value = false;
  }
};

// 删除用户
// 参数：id - 要删除的用户ID
const deleteUser = async (id) => {
  loading.value = true;
  try {
    await userService.delete(id);
    ElMessage.success('用户删除成功');
    await fetchUsers(); // 刷新用户列表
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.add-user-button-container {
  margin-bottom: 16px;
  text-align: left;
}

.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f6f3f3;
  border-radius: 8px;
}

.search-input {
  width: 240px !important;
}

.search-select {
  width: 180px !important;
}

.age-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.age-input {
  width: 120px !important;
}

.date-picker {
  width: 280px !important;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.custom-pagination .el-pagination__sizes {
  margin-right: 10px;
}

.el-table {
  background-color: #f5f7fa;
}

.el-table .cell {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #a1c1e1;
}

.el-table__body tr:hover > td {
  background-color: #f0f9ff;
}
</style>